import cv2
from PIL import Image
from pylab import*
import os
import psycopg2
import numpy as np
import matplotlib.pyplot as plt

class LBP:
    def __init__(self):
        pass

    #将图像载入，并转化为灰度图，获取图像灰度图的像素信息
    def describe(self,image):
        image_array=np.array(Image.open(image).convert('L'))
        return image_array

    #图像的LBP原始特征计算算法：将图像指定位置的像素与周围8个像素比较
    #比中心像素大的点赋值为1，比中心像素小的赋值为0，返回得到的二进制序列
    def calute_basic_lbp(self,image_array,i,j):
        sum=[]
        if image_array[i-1,j-1]>image_array[i,j]:
            sum.append(1)
        else:
            sum.append(0)
        if image_array[i-1,j]>image_array[i,j]:
            sum.append(1)
        else:
            sum.append(0)
        if image_array[i-1,j+1]>image_array[i,j]:
            sum.append(1)
        else:
            sum.append(0)
        if image_array[i,j-1]>image_array[i,j]:
            sum.append(1)
        else:
            sum.append(0)
        if image_array[i,j+1]>image_array[i,j]:
            sum.append(1)
        else:
            sum.append(0)
        if image_array[i+1,j-1]>image_array[i,j]:
            sum.append(1)
        else:
            sum.append(0)
        if image_array[i+1,j]>image_array[i,j]:
            sum.append(1)
        else:
            sum.append(0)
        if image_array[i+1,j+1]>image_array[i,j]:
            sum.append(1)
        else:
            sum.append(0)
        return sum

    #获取图像的LBP原始模式特征
    def lbp_basic(self,image_array):
        basic_array=np.zeros(image_array.shape, np.uint8)
        width=image_array.shape[0]
        height=image_array.shape[1]
        for i in range(1,width-1):
            for j in range(1,height-1):
                sum=self.calute_basic_lbp(image_array,i,j)
                bit_num=0
                result=0
                for s in sum:
                    result+=s<<bit_num
                    bit_num+=1
                basic_array[i,j]=result
        return basic_array


if __name__ == '__main__':
    # 连接数据库
    # 连接数据库
    conn = psycopg2.connect(
        host="YOUR_HOST",
        port="YOUR_PORT",
        user="YOUR_USER",
        password="YOUR_PASSWORD",
        database="YOUR_DATABASE"
    )

    # 删除表，避免之前提取的向量产生影响
    drop_table_query = """
        DROP TABLE feature_vectors ;
        """
    cursor = conn.cursor()
    cursor.execute(drop_table_query)
    conn.commit()

    # 创建表
    create_table_query = """
    CREATE TABLE IF NOT EXISTS feature_vectors (
        id SERIAL PRIMARY KEY,
        filename VARCHAR(255),
        vector TEXT,
        distance REAL
    );
    """
    cursor = conn.cursor()
    cursor.execute(create_table_query)
    conn.commit()

    # 插入数据
    dataset_path = r"E:\IMDB\wiki1"
    lbp = LBP()

    for filename in os.listdir(dataset_path):
        if filename.endswith(".jpg"):
            image_path = os.path.join(dataset_path, filename)
            image_array = lbp.describe(image_path)

            # 获取图像原始LBP特征，并输出特征向量
            basic_array = lbp.lbp_basic(image_array)
            h, _ = np.histogram(basic_array, bins=256, range=(0, 256))
            feature_vector = h.tolist()  # 转换为列表格式

            # 插入数据
            insert_query = "INSERT INTO feature_vectors (filename, vector) VALUES (%s, %s);"
            cursor.execute(insert_query, (filename, feature_vector))
            conn.commit()

    # 关闭连接
    cursor.close()
    conn.close
